<template>
	<view v-if="proviewInfo?.list?.length > 0" class="preview">
		<swiper @click="showMark" class="viewBox" :current="currentIndex" @change="swiperChange">
			<swiper-item v-for="(item,index) in proviewInfo.list" :key="index">
				<image v-if="proviewInfo.type === 'image'" show-menu-by-longpress lazy-load :src="item.url"
					:mode="item.direction === 0 ? 'aspectFit' : 'aspectFill'"></image>
				<video v-else autoplay loop muted :controls='true' object-fit='contain' show-mute-btn
					enable-play-gesture :src="item.video_url">
				</video>
			</swiper-item>
		</swiper>

		<view class="mask" v-if="markIsShow">
			<!--  #ifdef H5 -->
			<!-- 仅出现在 H5 平台下的代码 -->
			<view class="goBack" @click="goBack" :style="{top:'40rpx'}">
				<uni-icons type="back" color="#fff" size="20"></uni-icons>
			</view>
			<!--  #endif -->
			<!-- #ifndef H5 -->
			<!-- 除了 H5 平台，其它平台均存在的代码 -->
			<view class="goBack" @click="goBack" :style="{top:getStatusBarHeight() +'px'}">
				<uni-icons type="back" color="#fff" size="20"></uni-icons>
			</view>
			<!-- #endif -->
			
			<view class="count">
				{{currentIndex + 1}} / {{proviewInfo.list.length}}
			</view>
			<view class="footer">
				<view class="box" @click="collect">
					<uni-icons :color="isCollect ? '#32DBBA': ''" :type="isCollect ? 'star-filled': 'star'"
						size="28"></uni-icons>
					<view class="text">收藏</view>
				</view>

				<view class="box" @click="download">
					<uni-icons type="download" size="23"></uni-icons>
					<view class="text">下载</view>
				</view>

				<view class="box share">
					<button open-type="share" @click="webTost"></button>
					<uni-icons type="redo" size="28"></uni-icons>
					<view class="text">分享</view>
				</view>
			</view>
		</view>
	</view>
</template>
<script setup>
	import {
		getStatusBarHeight
	} from "@/utils/system.js"
	import {
		onLoad,
		onUnload,
		onShareAppMessage,
		onShareTimeline
	} from '@dcloudio/uni-app'
	import {
		ref,
		computed
	} from 'vue'
	import {
		cloudToUrl
	} from '@/utils/common.js'
	// 引入logo图
	import logo from '@/static/icon/logo.png'
	import MyURL from '@/utils/MyURL.js'
	const markIsShow = ref(true)
	const showMark = () => {
		markIsShow.value = !markIsShow.value
	}
	// 返回上一页
	const goBack = () => {
		const pages = getCurrentPages();
		if (pages.length <= 1) {
			uni.reLaunch({
				url: "/pages/index/index"
			})
		} else {
			uni.navigateBack({
				success: (res) => {},
				// 返回失败则返回首页
				fail: (err) => {
					uni.reLaunch({
						url: "/pages/index/index"
					})
				}
			})
		}
		
		
	}

	// 当前浏览的图片索引
	const currentIndex = ref(0)
	// 媒体类型
	let type = 'image'
	// 切换图片
	const swiperChange = (e) => {
		currentIndex.value = e.detail.current
		isCollect.value = getIsCollect()
		// 生成历史记录
		createHistory()
	}

	// 图片信息
	const proviewInfo = ref({})
	// 媒体类型
	let urlStr = 'video_url'
	// 收藏key名
	let index = 'collectInfo_video'
	// 历史key名
	let historyIndex = 'historyInfo_video'
	// 下载记录 key名
	let downloadIndex = 'downloadInfo_video'
	onLoad(async (e) => {
		if (e.type) {
			// 设置proviewInfo
			proviewInfo.value.type = e.type
			proviewInfo.value.list = [JSON.parse(decodeURIComponent(e.obj))]
			console.log(proviewInfo.value.list);
			// 如果过期重新请求连接
			// 使用 URL 对象解析
			const parsedUrl = new MyURL(proviewInfo.value.list[0].url);
			// 获取 expire_at 参数，并将其转换为数字类型
			const expireAt = parseInt(parsedUrl.searchParams.expire_at, 10);
			// 获取当前时间的时间戳（单位为秒）
			const currentTime = Math.floor(Date.now() / 1000);
			// 判断是否过期
			if (parsedUrl.search != '' && expireAt < currentTime) {
				console.log("链接已过期");
				const res = await cloudToUrl(proviewInfo.value.list[0].cloudUrl)
				proviewInfo.value.list[0].url = res
			} else {
				console.log("链接未过期");
			}
			proviewInfo.value.index = 0
			// console.log(proviewInfo.value)
		} else {
			// 获取缓存
			try {
				// 设置proviewInfo
				proviewInfo.value = uni.getStorageSync('previewInfo')
				currentIndex.value = proviewInfo.value.index
				type = proviewInfo.value.type
				// console.log(proviewInfo.value)
			} catch (e) {
				//TODO handle the exception
			}
		}
		if (type === 'image') {
			index = 'collectInfo_img'
			urlStr = 'cloudUrl'
			historyIndex = 'historyInfo_img'
			downloadIndex = 'downloadInfo_img'
		}
		// 缓存是否存在
		if (!uni.getStorageSync(index)) {
			uni.setStorageSync(index, [])
		}
		if (!uni.getStorageSync(historyIndex)) {
			uni.setStorageSync(historyIndex, [])
		}
		if (!uni.getStorageSync(downloadIndex)) {
			uni.setStorageSync(downloadIndex, [])
		}
		// 读取收藏状态
		isCollect.value = getIsCollect()
		// 生成历史记录
		createHistory()


	})


	const isCollect = ref(false)
	// 收藏按钮回调
	const collect = () => {
		// 缓存中的收藏数据 Array
		let collectInfo = uni.getStorageSync(index)
		// 当前展示图片项 Object
		let collectOption = proviewInfo.value.list[currentIndex.value]
		if (!getIsCollect(true)) {
			uni.setStorageSync(index, [...collectInfo, collectOption])
		}
		isCollect.value = !isCollect.value
	}
	// 返回是否已经收藏
	// 如果传入参数 isdelete 为 true 则查到时删除缓存中的数据
	const getIsCollect = (isdelete = false) => {
		// 缓存中的收藏数据 Array
		let collectInfo = uni.getStorageSync(index)
		// 当前展示图片项 Object
		let collectOption = proviewInfo.value.list[currentIndex.value]
		let isFind = false
		for (let i = 0; i < collectInfo.length; i++) {
			const item = collectInfo[i]
			if (item[urlStr] == collectOption[urlStr]) {
				if (isdelete) {
					collectInfo.splice(i, 1)
					uni.setStorageSync(index, collectInfo)
				}
				isFind = true
				break
			}
		}
		return isFind

	}


	// 下载
	const download = async () => {
		createDownload()
		// 当前展示图片项 Object
		let collectOption = proviewInfo.value.list[currentIndex.value]
		let url = ''
		if (type === 'image') {
			url = collectOption.url
		} else {
			url = collectOption.video_url
		}
		// #ifdef H5
		uni.showModal({
			content: "请长按保存壁纸",
			showCancel: false
		})
		// #endif
		// #ifndef H5
		// 下载网络资源
		try {
			uni.showLoading({
				title: "下载中...",
				mask: true
			})
			// console.log('下载url:', url)
			const tempFilePath = await getMediumInfo(url)
			await saveMediumToPhotosAlbum(tempFilePath)
			uni.showToast({
				title: "保存成功，请到相册查看",
				icon: "none"
			})
		} catch (e) {
			//TODO handle the exception
			console.error('下载图片失败', e)
			// 处理保存图片失败
			if (e.errMsg === 'saveImageToPhotosAlbum:fail cancel' || e.errMsg ===
				'saveVideoToPhotosAlbum:fail cancel') {
				uni.showToast({
					title: '保存失败，请重新点击下载',
					icon: "none"
				});
			} else {
				// 处理未授权保存到相册
				const {
					confirm
				} = await showModal({
					title: "授权提示",
					content: "需要授权保存相册"
				});

				if (confirm) {
					const setting = await openSetting();
					if (setting.authSetting['scope.writePhotosAlbum']) {
						uni.showToast({
							title: "获取授权成功",
							icon: "none"
						});
					} else {
						uni.showToast({
							title: "获取权限失败",
							icon: "none"
						});
					}
				}
			}
		} finally {
			uni.hideLoading()
		}
		// #endif
	}
	// 封装打开设置为Promise
	function openSetting() {
		return new Promise((resolve, reject) => {
			uni.openSetting({
				success: resolve,
				fail: reject
			});
		});
	}
	// 封装保存图片/视频到相册为Promise
	function saveMediumToPhotosAlbum(filePath) {
		return new Promise((resolve, reject) => {
			if (type === 'image') {
				uni.saveImageToPhotosAlbum({
					filePath: filePath,
					success: resolve,
					fail: reject
				});
			} else {
				uni.saveVideoToPhotosAlbum({
					filePath: filePath,
					success: resolve,
					fail: reject
				});
			}


		});
	}
	// 封装 获取图片/视频信息为Promise 返回临时文件路径
	function getMediumInfo(url) {
		return new Promise((resolve, reject) => {
			if (type === 'image') {
				uni.getImageInfo({
					src: url,
					success: (res) => {
						resolve(res.path);
					},
					fail: (err) => {
						reject(err);
					}
				});
			} else {
				uni.downloadFile({
					url: url,
					success: (res) => {
						if (res.statusCode === 200) {
							resolve(res.tempFilePath);
						} else {
							reject(res)
						}
					},
					fail: (err) => {
						reject(err);
					}
				});
			}

		});
	}

	const webTost = () => {
		// #ifdef H5
		let collectOption = {
			...proviewInfo.value.list[currentIndex.value]
		}
		// 减少不必要的字段,缩短url长度
		delete collectOption.desc
		delete collectOption.count
		delete collectOption.status
		delete collectOption.timestamp
		delete collectOption.title
		let collectOptionStr = JSON.stringify(collectOption)
		// console.log(collectOption)
		// 获取当前页面url
		let url = `${window.location.href}?type=${type}&obj=${encodeURIComponent(collectOptionStr)}`
		// console.log(`${url}?type=${type}&obj=${encodeURIComponent(collectOptionStr)}`)

		// 复制到手机剪贴板
		uni.setClipboardData({
			data: url,
			success: function() {
				uni.showToast({
					title: '分享链接已复制',
					icon: "none"
				});
			},
			fail: function() {
				uni.showToast({
					title: '分享链接复制失败',
					icon: "none"
				})
			}
		});

		// #endif
	}

	//分享给好友
	onShareAppMessage(() => {
		// 当前展示图片项 Object
		// 对象转字符串
		let collectOption = proviewInfo.value.list[currentIndex.value]
		let collectOptionStr = JSON.stringify(collectOption)
		return {
			title: "Down壁纸 发现一张绝美壁纸！",
			path: `/pages/preview/preview?type=${type}&obj=${encodeURIComponent(collectOptionStr)}`,
			imageUrl: collectOption.url || logo

		}
	})
	//分享给朋友圈
	onShareTimeline(() => {
		let collectOption = proviewInfo.value.list[currentIndex.value]
		let collectOptionStr = JSON.stringify(collectOption)
		return {
			title: 'Down壁纸 发现一张绝美壁纸！',
			query: `/pages/preview/preview?type=${type}&obj=${encodeURIComponent(collectOptionStr)}`,
			imageUrl: collectOption.url || logo
		}
	})
	// 生成下载记录
	const createDownload = () => {
		// ！！！ 频繁去重导致翻页卡顿，暂时不生成历史记录，在个人页初始化或打开历史记录页时去重
		// // 缓存中的历史数据 Array
		let downloadInfo = uni.getStorageSync(downloadIndex)
		// // 当前展示图片项 Object
		let downloadOption = proviewInfo.value.list[currentIndex.value]
		// 直接添加记录
		uni.setStorageSync(downloadIndex, [...downloadInfo, downloadOption])
	}
	// 生成浏览历史
	const createHistory = () => {
		// ！！！ 频繁去重导致翻页卡顿，暂时不生成历史记录，在个人页初始化或打开历史记录页时去重
		// // 缓存中的历史数据 Array
		let historyInfo = uni.getStorageSync(historyIndex)
		// // 当前展示图片项 Object
		let historyOption = proviewInfo.value.list[currentIndex.value]

		// 直接添加记录
		uni.setStorageSync(historyIndex, [...historyInfo, historyOption])


	}

	// 退出页面
	onUnload(() => {
		uni.removeStorageSync('previewInfo')
	})
</script>
<script>
	import { getCurrentInstance } from 'vue'
	export default {
		data() {
			return {
				instance: getCurrentInstance()
			}
		},
		onLoad() {
			this.instance.onShareAppMessage[1] = this.instance.onShareAppMessage[0]
			this.instance.onShareTimeline[1] = this.instance.onShareTimeline[0]
		}
	}
	
</script>
<style lang="scss" scoped>
	.preview {
		width: 100%;
		height: 100vh;
		position: relative;

		swiper {
			width: 100%;
			height: 100%;

			image {
				width: 100%;
				height: 100%;
			}

			video {
				width: 100%;
				height: 100%;
			}
		}

		.mask {
			&>view {
				position: absolute;
				left: 0;
				right: 0;
				margin: auto;
				color: #fff;
				width: fit-content;
			}

			.goBack {
				width: 38px;
				height: 38px;
				background: rgba(0, 0, 0, 0.5);
				left: 30rpx;
				margin-left: 0;
				border-radius: 100px;
				top: 0;
				backdrop-filter: blur(10rpx);
				border: 1rpx solid rgba(255, 255, 255, 0.3);
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.count {
				top: 10vh;
				background: rgba(0, 0, 0, 0.3);
				font-size: 28rpx;
				border-radius: 40rpx;
				padding: 8rpx 28rpx;
				backdrop-filter: blur(10rpx);
			}

			.footer {
				background: rgba(255, 255, 255, 0.8);
				bottom: 10vh;
				width: 65vw;
				height: 120rpx;
				border-radius: 120rpx;
				color: #000;
				display: flex;
				justify-content: space-around;
				align-items: center;
				box-shadow: 0 2rpx 0 rgba(0, 0, 0, 0.1);
				backdrop-filter: blur(20rpx);

				.share {
					position: relative;

					button {
						width: 100%;
						height: 100%;
						position: absolute;
						z-index: 99;
						opacity: 0;

					}
				}

				.box {
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					padding: 2rpx 12rpx;


					.text {
						font-size: 26rpx;
						color: $text-font-color-2;
					}
				}
			}

		}

	}
</style>